<?php


namespace App\Foundation\Utils;

class Aes
{
    private $iv = "";//iv的长度要根据加密方式和模式来定,aes-128-cbc偏移量的是16位
    private $key = "";
    function __construct($key, $iv)
    {
        $this->key = $key;
        $this->iv = $iv;
    }

    //加密返回客户端的数据
    public function encrypt($input){
        $data = $this->String2Hex($input);
        return base64_encode(openssl_encrypt($data, 'AES-128-CBC', $this->key, OPENSSL_RAW_DATA, $this->iv));
    }
    //解密客户端传输数据
    public function decrypt($input){
        $data = openssl_decrypt(base64_decode($input), 'AES-128-CBC', $this->key, OPENSSL_RAW_DATA, $this->iv);
        $data = $this->Hex2String($data);
        if($data){
            return json_decode($data,true);
        }else{
            return false;
        }
    }
    //字符串转16进制
    public function String2Hex($string){
        $hex='';
        for ($i=0; $i < strlen($string); $i++){
            $hex .= dechex(ord($string[$i]));
        }
        return $hex;
    }
    //16进制转字符串
    public function Hex2String($hex){
        $string='';
        for ($i=0; $i < strlen($hex)-1; $i+=2){
            $string .= chr(hexdec($hex[$i].$hex[$i+1]));
        }
        return $string;
    }

}